#ifndef MODBUSCLIENT_H
#define MODBUSCLIENT_H

#include <QThread>
#include <QString>
#include <QMutex>
#include <QQueue>
#include <QWaitCondition>
#include <QVector>
#include <modbus.h>

enum  OperationType {
    ReadHoldingRegisters,
    WriteHoldingRegisters,
    WriteSingleCoil,
    WriteSingleCoilS,
    ReadCoils,
    NONE_OP
    // 添加其他类型...
};
enum  ModbusMode {
    RTU,
    TCP
};
typedef struct
{
    uint8_t device_id;
    uint8_t  len;
    uint8_t  date_8[100];
    uint16_t addres;
    uint16_t date[100];
    int  opType;
    bool   opResult;
}ModbusRequest;


class ModbusClient : public QThread {
    Q_OBJECT

public:
    explicit ModbusClient(QObject *parent = nullptr);
    ~ModbusClient();

    bool init(ModbusMode mode, const QString &addressOrPort, int baudOrPort);
    void stopPolling();
    void sendCommand(const ModbusRequest &request);
    void sendTestComand();
    void addRequest(const ModbusRequest &request);  // 添加读取/写入请求

signals:
    void dataReceived(int sensorId, const QVector<uint16_t> &data);
    void errorOccurred(const QString &error);
    void request_receive_data(ModbusRequest);
protected:
    void run() override;

private:
    ModbusMode mode;
    modbus_t *ctx;
    QMutex mutex;
    QVector<ModbusRequest> requests;  // 存储所有请求
    QQueue<ModbusRequest> commandQueue;  // 存储待发送的命令队列
    QWaitCondition commandCondition;  // 用于唤醒线程处理命令的条件变量
};

#endif // MODBUSCLIENT_H
